package cn.edu.pku.ss.situationawareperceiver;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SensorHandler extends DefaultHandler{
	
	private Sensor sensor;
	private List<Sensor> sensorConfiguration;
	private List<List<Sensor>> sensorConfigurations;
	
	private final int NAME = 1;
	private final int CONTEXTTYPE = 2;
	private int currentState = 0;
	
	public SensorHandler()
	{
		sensorConfigurations = new ArrayList<List<Sensor>>();
	}
	
	public List<Sensor> getSensorConfiguration(int configurationID)
	{
		return sensorConfigurations.get(configurationID);
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if(localName.equals("sensorConfiguration"))
		{
			sensorConfiguration = new ArrayList<Sensor>();
			return;
		}
		if(localName.equals("sensor"))
		{
			sensor = new Sensor();
			return;
		}
		if(localName.equals("name"))
		{
			currentState = NAME;
			return;
		}
		if(localName.equals("contextType"))
		{
			currentState = CONTEXTTYPE;
			return;
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		String content = new String(ch, start, length);
		switch (currentState) {
		case NAME:
			sensor.name = content;
			currentState = 0;
			break;
		case CONTEXTTYPE:
			sensor.contextType = ContextHandler.contextTypeMapper.get(content);
			currentState = 0;
			break;
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		if(localName.equals("sensorConfiguration"))
		{
			sensorConfigurations.add(sensorConfiguration);
			return;
		}
		if(localName.equals("sensor"))
		{
			sensorConfiguration.add(sensor);
			return;
		}
	}
}
